import React from 'react'
import { Animated, StyleSheet, BackHandler } from 'react-native'
import RootSiblings from 'react-native-root-siblings'
import Picker from 'react-native-picker'
import CustomButton from '../components/button/CustomButton'

var sibling = null
const opacityAnimate = new Animated.Value(0) // 动画 值初始化
const animateDuration = 300
let backHandler
export default function showPicker(pickerData) {
  if (sibling) {
    return
  }
  backHandler = BackHandler.addEventListener('hardwareBackPress', handleBackPress)
  sibling = new RootSiblings(pickerMaskView(), () => {
    initPicker(pickerData)
    opacityAnimate.setValue(0)
    // 开启动画
    Animated.timing(opacityAnimate, {
      toValue: 1,
      duration: animateDuration
    }).start()
  })
}

function handleBackPress() {
  maskClick()
  return true
}

function initPicker(pickerData) {

  Picker.init({
    pickerData: pickerData.pickerData,
    selectedValue: pickerData.selectedValue,
    pickerTitleText: pickerData.pickerTitleText,
    pickerConfirmBtnText: '确认',
    pickerConfirmBtnColor: [107, 180, 106, 1],
    pickerCancelBtnColor: [153, 153, 153, 1],
    pickerCancelBtnText: '取消',
    pickerBg: [255, 255, 255, 1],
    pickerToolBarBg: [255, 255, 255, 1],
    onPickerConfirm: (confirmData) => {
      console.log(confirmData)
      pickerData.onConfirm && pickerData.onConfirm(confirmData)
      closePicker()
    },
    onPickerCancel: data => {
      closePicker()
    },
    onPickerSelect: data => {
    }
  })
  Picker.show()
}

function maskClick() {
  closePicker()
  Picker.hideAnimated()
}

function pickerMaskView() {
  return (
    <Animated.View style={[styles.pickerMask, { opacity: opacityAnimate }]}>
      <CustomButton onPress={maskClick} style={styles.maskBtnView} activeOpacity={1} />
    </Animated.View>
  )
}

/**
 * 关闭Picker
 *
 */
function closePicker(pickerClosed) {
  Animated.timing(
    opacityAnimate,
    {
      toValue: 0,
      duration: animateDuration
    }
  ).start(() => {
    hidePicker()
    pickerClosed && pickerClosed()
  })
}

function hidePicker() {
  if (sibling instanceof RootSiblings) {
    sibling.destroy()
    sibling = null
    backHandler && backHandler.remove()
  }
}

const styles = StyleSheet.create({
  pickerMask: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    backgroundColor: 'rgba(0,0,0,0.7)'
  },
  maskBtnView: {
    width: '100%',
    height: '100%'
  }
})
